package org.sink.study.java8;

        import org.junit.Test;

        import java.util.ArrayList;
        import java.util.Arrays;
        import java.util.List;
        import java.util.stream.Collectors;

public class CollectionOperationCompare {


    @Test
    public void testFilter() {
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

        //java8之前
        List<Integer> filtered1 = new ArrayList<>();
        for (Integer integer : integers) {
            if (integer > 3) {
                filtered1.add(integer);
            }
        }
        System.out.println(filtered1);

        //java8之后
        List<Integer> filtered2 = integers.stream().filter(i -> i > 3).collect(Collectors.toList());
        System.out.println(filtered2);

    }

    @Test
    public void testSum() {
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

        int sum1 = 0;
        for (Integer integer : integers) {
            if (integer > 2) {
                sum1 += integer;
            }
        }
        System.out.println(sum1);

        int sum2 = integers.stream().filter(i -> i > 2).mapToInt(i -> i).sum();
        System.out.println(sum2);

    }

    /**
     * 输出所有元素的2倍大于3的元素
     *
     */
    @Test
    public void testForEach() {
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

        for (Integer integer : integers) {
            if (2 * integer > 3) {
                System.out.println(integer);
            }
        }

        integers.stream().filter(i -> 2 * i > 3).forEach(System.out::println);

    }


}
